layui.define(['jquery', 'pearOper', 'jquery_cookie'], function (exports) {
    var $ = layui.jquery;
    var pearOper = layui.pearOper;
    var $_c = layui.jquery_cookie($);
    var tool = {
        pear: {
            msg: function (position, type, title) {
                pearOper.notice({position: position, type: type, title: title});
            },
            success: function (msg) {
                tool.pear.msg('right-top', "success", msg);
            },
            fail: function (msg) {
                tool.pear.msg('right-top', "failure", msg);
            },
            error: function (msg) {
                tool.pear.msg('right-top', "warning", msg);
            }
        },
        cookies: {
            set: function (key, val, day) {
                $_c.cookie(key, val, {expires: 7, path: '/'});
            },
            get: function (key) {
                return $_c.cookie(key);
            },
            del: function (key) {
                $_c.cookie(key, null);
            }
        },
        isBlank: function (value) {
            if (value != null) {
                value = $.trim(value);
                if (value !== '') {
                    return false;
                }
            }
            return true;
        },
        serializeObject: function (_$) {//将form转json对象
            var o = {};
            var a = _$.serializeArray();
            $.each(a, function (index, _this) {
                if (o[_this.name]) {
                    if (!o[_this.name].push) {
                        o[_this.name] = [o[_this.name]];
                    }
                    o[_this.name].push(_this.value || '');
                } else {
                    o[_this.name] = _this.value || '';
                }
            });
            return o;
        },
        JsonToHtmlValById: function (json, parent) {//json通过id注入到元素的value
            for (var key in json) {
                var value = json[key];
                var childId = "#" + key;
                if (parent !== undefined) {
                    if (typeof parent === "object") {
                        parent.find(childId).val(value);
                    } else
                        $("#" + parent).find(childId).val(value);
                } else
                    $(childId).val(value);
            }
        },
        JsonToHtmlValByName: function (json, parent) {//json通过name注入到元素的value
            for (var key in json) {
                var value = json[key];
                if (parent !== undefined) {
                    if (typeof parent === "object") {
                        parent.find("input[name='" + key + "']").val(value);
                    } else
                        $("#" + parent).find("input[name='" + key + "']").val(value);
                } else
                    $("input[name='" + key + "']").val(value);
            }
        },
        JsonToHtmlTextById: function (json, parent) {//json通过id注入到元素的text
            for (var key in json) {
                var value = json[key];
                var childId = "#" + key;
                if (parent !== undefined) {
                    if (typeof parent === "object") {
                        parent.find(childId).text(value);
                    } else
                        $("#" + parent).find(childId).text(value);
                } else
                    $(childId).text(value);
            }
        },
        getLayuiTableHeight: function (other) {//获取窗口高度，名称起错了，凑乎用吧
            return other == null ? $(window).height() : $(window).height() - other;
        },
        preview: function (src, size = undefined) {//图片查看工具
            var img = new Image();
            img.src = src;
            var loadIndex = parent.layer.load(0);
            img.onerror = () => {
                parent.layer.close(loadIndex);
                parent.layer.msg("图片加载失败");
            };
            img.onload = () => {
                parent.layer.close(loadIndex);
                var height, width;
                var imgHtml = "<img src='" + src + "' ";
                if (size === undefined) {//显示图片原始大小
                    //获取当前窗口大小
                    var winHeight = $(tool.getParent().window).height() - 100;
                    var winWidth = $(tool.getParent().window).width() - 50;
                    if (img.height >= winHeight)//获取图片高度
                        height = winHeight;
                    else
                        height = img.height;
                    if (img.width >= winWidth)//获取图片宽度
                        width = winWidth;
                    else
                        width = img.width;
                    imgHtml += " />";
                } else {//自定义展示图片大小
                    height = size.height;
                    width = size.width;
                    imgHtml += " width='" + width + "px' height='" + height + "px' />";
                }
                //弹出层
                tool.getParent().layer.open({
                    type: 1,
                    shade: 0.8,
                    offset: 'auto',
                    area: [width + 'px', height + 50 + 'px'],
                    shadeClose: true,
                    scrollbar: false,
                    title: "图片预览", //不显示标题
                    content: imgHtml, //捕获的元素，注意：最好该指定的元素要存放在body最外层，否则可能被其它的相对元素所影响
                    cancel: function () {
                        //layer.msg('捕获就是从页面已经存在的元素上，包裹layer的结构', { time: 5000, icon: 6 });
                    }
                });
            }
        },
        getParent: function () {//获取最顶的parent
            var par = parent;
            $.each(parent, function () {
                par = par.parent;
            });
            return par;
        },
        imgsUpload: function (json, _addBack, _delBack) {//图片上传工具
            var div = json.div;
            var sum = json.sum;
            var fileList = json.fileList;
            var renew = json.renew;
            var imgSize = json.size != null ? json.size : 1024 * 1024 * 2;
            let size = div[0].clientHeight;
            let count = 0;
            if (fileList != null && Object.keys(fileList).length > 0) {
                for (var key in fileList) {
                    addImg(fileList[key], key);
                }
            } else if (sum > count) {
                addInit();
            }

            function addInit(_Renew, _RenewChange) {
                div.append('<div class="add">' +
                    '<input type="file" name="file" style="display:none; " />' +
                    '<i class="layui-icon layui-icon-add-circle-fine" style="font-size: ' + size + 'px;color: rgba(0,0,0,0.35);"></i>' +
                    '</div>');
                let _this = div.find(".add");
                let file = div.find("[name='file']");
                //选择完文件触发
                file[0].onchange = function () {
                    var fileData = this.files[0];
                    if (fileData != null)
                        if (!/image\/\w+/.test(fileData.type)) {
                            tool.pear.error("请选择正确的图片！");
                        } else if (fileData.size > imgSize) {
                            tool.pear.error("该图片过大！");
                        } else {
                            //初始化一个文件读取对象
                            var reader = new FileReader();
                            //读取文件数据
                            reader.readAsDataURL(fileData);
                            //读取完毕,相当于加载的过程
                            reader.onload = function (oFREvent) {
                                _this.remove();
                                //this.result就是使用base64表示的图片信息
                                let base64 = oFREvent.target.result;
                                let name = addImg(base64, fileData);
                                if (typeof _addBack === 'function')
                                    _addBack(fileData, name);
                            }
                            if (typeof _RenewChange === 'function')
                                _RenewChange(_this, file);
                        }
                }
                div.find(".add i").click(function () {
                    file.click();
                })
                if (typeof _Renew === 'function')
                    _Renew(_this, file);
            }

            function addImg(src, fileData) {
                var name = "img_" + new Date().getTime();
                div.append('<img name="' + name + '" width="115px" height="115px" src="' + src + '">');
                count++;
                div.find("[name='" + name + "']").click(function () {
                    if (renew)
                        layer.confirm('你要对这个图片做什么？', {
                            btn: ['查看', '重新上传'] //按钮
                        }, function () {
                            tool.preview(src);
                        }, function () {
                            addInit(function (_this, file) {
                                file.click();
                                _this.remove();
                            }, function () {
                                delImg(name, fileData);
                            });
                        });
                    else
                        layer.confirm('你要对这个图片做什么？', {
                            btn: ['查看', '删除'] //按钮
                        }, function () {
                            tool.preview(src);
                        }, function () {
                            delImg(name, fileData);
                            if (sum > count)
                                addInit();
                        });
                })
                if (sum > count)
                    addInit();
                return name;
            }

            function delImg(name, fileData) {
                count--;
                div.find("[name='" + name + "']").remove();
                if (typeof _delBack === 'function')
                    _delBack(fileData, name);
            }
        }
    };

    exports('tool', tool)
});
